// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// I [author] rhyme_lph
// q [email]  rhymelph@gmail.com
// Y [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/salary_user_working_days_entity.dart';
import 'package:finance_app/src/http_service/http_payslips_service.dart';
import 'package:finance_app/src/mixin/salary_date_select_mixin.dart';
import 'package:finance_app/src/provider/dashboard_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/payroll_provider.dart';
import 'package:finance_app/src/router_gen/override_route_providers.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';

class SetSalaryPeriodProvider
    extends BaseProvider<List<SalaryUserWorkingDaysEntity>>
    with SalaryDateSelectMixin {
  List<int> ids = [];
  List<EmployeeContactEntity> currentData;
  @override
  Future get dataFuture => HttpPayslipsService.calculateWorkingDays(
      ids,
      DateTimeUtils.formatDateTime(from, 'yyyy-MM-dd'),
      DateTimeUtils.formatDateTime(to, 'yyyy-MM-dd'));

  @override
  void initState() {
    ids = currentData.map((e) => e.id).toList();
    super.initState();
  }

  void onDone() {
    obtainContext?.call((context) async {
      String content =
          'For ${TimeUtils.formatDateTime(from, "dd MMM yyyy")} to ${TimeUtils.formatDateTime(to, "dd MMM yyyy")}';
      bool confirmed =
          await showGeneratePayslipConfirmationBottomSheet(context, content);
      if (confirmed == null) {
        return;
      }
      bool isSuccess = false;

      List salaryUserWorkingDays = data
          .where((x) => !x.beforeHiringDate)
          .map((e) => {
                'id': e.id,
                'name': e.name,
                'days': e.days,
              })
          .toList();

      await post(
          HttpPayslipsService.payslipsGenerate(
              salaryUserWorkingDays,
              DateTimeUtils.formatDateTime(from, 'yyyy-MM-dd'),
              DateTimeUtils.formatDateTime(to, 'yyyy-MM-dd')),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        isSuccess = true;
      });
      if (isSuccess == true) {
        await showPayslipsRunRequestSuccessBottomSheet(context);
        Providers.get<HrAndPayrollProvider>(
                RouterGenProviders.hrAndPayrollPage, null)
            ?.getChildProvider<PayrollProvider>()
            ?.refreshController
            ?.requestRefresh();

        if (!Config.hasPermission(PermissionUtils.homeDashboard))
          Config.dashboardProvider
              ?.getChildProvider<HrAndPayrollProvider>()
              ?.getChildProvider<PayrollProvider>()
              ?.refreshController
              ?.requestRefresh();
        Navigator.of(context)..pop()..pop();
      }
    });
  }

  void onNavLeaveDetails() async {
    final result =
        await Routes.navigateTo(RouterGenProviders.leaveDetailsPage, params: {
      'data': currentData,
      'startDate': DateTimeUtils.formatDateTime(from, 'yyyy-MM-dd'),
      'endDate': DateTimeUtils.formatDateTime(to, 'yyyy-MM-dd')
    });
  }

  void initData(List<EmployeeContactEntity> data) {
    currentData = data;
  }

  @override
  void onRequestRefresh() {
    post(dataFuture,
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) {
      data = transformData(
          getEntityFromResult<List<SalaryUserWorkingDaysEntity>>(result),
          false);
      update();
    });
  }

  @override
  FutureOr<List<SalaryUserWorkingDaysEntity>> transformData(
      List<SalaryUserWorkingDaysEntity> d, bool isCache) {
    // currentData.forEach((employee) {
    //   print('Employee ${employee.name}  ${employee.joinedAt}');
    //   print('from date ${from}');
    //   DateTime joinedDate = DateTime.tryParse(employee.joinedAt ?? '');
    //   if (joinedDate != null && from != null && joinedDate.isAfter(from)) {
    //     d.firstWhere((element) => element.id == employee.id).beforeHiringDate =
    //         true;
    //   }
    // });
    return super.transformData(d, isCache);
  }
}
